<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Map editor</title>
    <!--[if IE]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
    <!--script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script-->
    <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
    <!--script type="text/javascript" src="map_data/map_data.json"></script-->
    <style>
      ul { margin: 0}
      ul li {list-style: none; padding: 0 5px; background: #000; float: left}
      ul li:nth-child(odd) {background: #bdc3c7}
      ul li:nth-child(even) {background: #ecf0f1}
      canvas {float: left}
      #action {float: left}
      
      input.size {margin: 5px 0 0 20px; padding: 10px; border: 2px solid #000; color: #000}
      input.size:focus {background: #FFF; color: #000}
      button.btn {border: 2px solid #000; background: none; padding: 10px 20px; margin: 5px 0 0 20px}
      button.btn:hover {background: #000; color: #FFF}
    </style>
  </head>
  <body onload = "init();">
    <ul>
      <li><img src = "img/map/BIG_PIG.png" id="12" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/SMALL_PIG.png" id="13" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/BI_NGO.png" id="6" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/BLACK_BIRD_BULLET.png" id="10" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/YELLOW_BIRD_BULLET.png" id="11" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/DONUT.png" id="7" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/LAND.png" id="1" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/STRAWBERRY.png" id="9" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/WOOD.png" id="2" width="50" draggable="true" ondragstart="dragStart(event)"/></li>
      <li><img src = "img/map/WOOD.png" id="5" width="50" draggable="true" title="ROCK" ondragstart="dragStart(event)"/></li>
    </ul>
    <p id="error"></p>
    <canvas id="canvas" width="400" height="300" style="border: 1px solid #000">
      This text is displayed if your browser does not support HTML5 Canvas.
    </canvas>
    <div id="action">
        <input type="text" placeholder="Width" id="width" class="size"/><br />
        <input type="text" placeholder="Width" id="height" class="size"/><br />
        <button class="btn" id="new">New</button><br />
        
        <button class="btn" id="save" onclick="Save()">Save</button><br />
    </div>
  </body>
</html>
<script>
  var canvas;
  var ctx;
  
  var x = 0;
  var y = 0;
  
  var dragok = false;
  
  var vWidth = 800;
  var vHeight = 600;
  
  var COLS = 100;
  var ROWS = 25;
  var CELL_SIZE = 28;
  var LEVEL = 0;
  
  var data = [];
  var img, bg;
  var images = [];
  var index = 0;
  
  var offsetX = 0;
  var offsetY = 0;  
  
  var WIDTH = COLS * CELL_SIZE;
  var HEIGHT = ROWS * CELL_SIZE;
  
  //$(document).ready(function() {
    
  //});
  
  function clear() {
  	ctx.clearRect(0, 0, COLS * CELL_SIZE, ROWS * CELL_SIZE);
  }
    /*
  $("#new").click(function() {
       var w = $("#width").val();
       var h = $("#height").val();
       console.log(w);
       if(isNaN(w) || isNaN(h)) {
        $("#error").text("Width and Heiight must is a number");
        return;
       }
       COLS = parseInt(w / CELL_SIZE);
       ROWS = parseInt(h / CELL_SIZE);
       
       //init();
    });
    */
  function init() {
  	canvas = document.getElementById("canvas");
  	ctx = canvas.getContext('2d');
  	
  	canvas.tabIndex = 1;
  
  	img = new Image();
  	//img.src = "1.png";
  	
  	bg = new Image();
  	bg.src = "img/map/background.png";
  	
  	bg.onload = function() {}
  	img.onload = function() {}
  
  	WIDTH = COLS * CELL_SIZE;
  	HEIGHT = ROWS * CELL_SIZE;
  	
  	canvas.width = vWidth;
  	canvas.height = vHeight;
  
  	for (var i = 0; i < ROWS; i++) {
  		var a = [];
  		for (var j = 0; j < COLS; j++) {
  			//
  			a[j] = {
  				top: i * CELL_SIZE,
  				left: j * CELL_SIZE,
  				value: 0
  			};                
  		}
  		data.push(a);
  	}
  	
  	canvas.addEventListener("dragover", function(e) {
  		e.preventDefault();
  	}, false);
  
  	canvas.addEventListener("drop", getfiles, false);
  	
  	offsetY = HEIGHT - vHeight;
  	return setInterval(draw, 10);
  }
  
  function draw() {
  	clear();
  	ctx.save();
  	ctx.translate(-offsetX, -offsetY);
  	drawBackground();
  	if (images.length > 0) {
  		for (var i = 0; i < images.length; i++) {
  			var img = images[i];
  			ctx.drawImage(img.image, img.x, img.y, CELL_SIZE, CELL_SIZE);
  		}
  	}
  	ctx.restore();
  }
  
  function drawBackground() {
    
  	ctx.drawImage(bg, offsetX, offsetY, vWidth, vHeight, offsetX, offsetY, vWidth, vHeight);
    
    var left = (offsetX * 2) % bg.width;
	var top = offsetY * 2;
    
	if (vWidth > bg.width - offsetX) {

		var bW = bg.width - offsetX;
		var vW = bW / 2;
		ctx.drawImage(bg, offsetX, offsetY, bW, vHeight, 0, offsetY, bW, vHeight);

		//bW = vWidth - bW;
		ctx.drawImage(bg, 0, offsetY, (vWidth - bW), vHeight, bW, offsetY, (vWidth - bW), vHeight);
   } else {
  	     ctx.drawImage(bg, offsetX, offsetY, vWidth, vHeight, offsetX, offsetY, vWidth, vHeight);
  	}
    
  }
  
  function dragStart(e) {
  	e.dataTransfer.setData("text/uri-list", e.target.src);
  	e.dataTransfer.setData("id", e.target.id);
  }
  
  function getfiles(e) {    
  	var src = e.dataTransfer.getData("text/uri-list");
  	var id = e.dataTransfer.getData("id");
  	var position = $("canvas").position();
  	var x = e.clientX - position.left;
  	var y = e.clientY - position.top;

  	for (var i = 0; i < ROWS; i++) {
  		for (var j = 0; j < COLS; j++) {
              
  			if (e.clientX - position.left > data[i][j].left - offsetX && e.clientX - position.left < data[i][j].left + CELL_SIZE - offsetX) {
  				x = data[i][j].left;
  				if (e.clientY - position.top > data[i][j].top - offsetY && e.clientY - position.top < data[i][j].top +CELL_SIZE - offsetY) {
  					y = data[i][j].top;
                    data[i][j].value = id;
  					break;
  				}
  			}
  		}
  	}
  
  	img.src = src;
  	var im = new Image();
  	im.src = src;
  	im.onload = function() {}
  	var image1 = {
  		x: x,
  		y: y,
  		image: im,
  		id: id
  	}
  	images.push(image1);
  }
  
  $("canvas").mousedown(function myDown(e) {
  	var position = $("canvas").position();
  
  	var xCanvas = e.clientX - position.left;
  	var yCanvas = e.clientY - position.top;
  	
  	var iData = 0;
  	var jData = 0;
  	
  	// index of data
  	for(var i = 0; i < ROWS; i++) {
  		for (var j = 0; j < COLS; j++) {
  		
  			var dataI = data[i][j].left - offsetX;
  			var dataJ = data[i][j].top - offsetY;
  			
  			if(xCanvas - dataI >= 0 && xCanvas - dataI <= CELL_SIZE
  				&& yCanvas - dataJ >= 0 && yCanvas - dataJ <= CELL_SIZE) {
  				iData = i;
  				jData = j;
  				data[i][j].value = 0;
  			}
  		}
  	}
  	
  	var x = 0;
  	var y = 0;
  	//
  	if (images.length > 0) {
  		for (var i = 0; i < images.length; i++) {
  				
  			var imageX = images[i].x - offsetX;
  			var imageY = images[i].y - offsetY;
  			
  			if (xCanvas - imageX >= 0 && xCanvas - imageX <= CELL_SIZE && yCanvas - imageY >= 0 && yCanvas - imageY <= CELL_SIZE) {
  				
  				x = imageX;
  				y = imageY;
  				index = i;
  				break;
  			}
  		}
             
      	if (xCanvas >= x && xCanvas <= x + CELL_SIZE &&
      		yCanvas >= y && yCanvas <= y + CELL_SIZE) {
      		console.log("Selected object");
      		dragok = true;
      		$("canvas").mousemove(function myMove(e) {
      			canvas.style.cursor = 'move';		
      
      			if (dragok) {
      				for (var i = 0; i < ROWS; i++) {
      					for (var j = 0; j < COLS; j++) {
      						if (e.clientX - position.left > data[i][j].left - offsetX && e.clientX - position.left < data[i][j].left + CELL_SIZE - offsetX) {
      							images[index].x = data[i][j].left;
      							if (e.clientY - position.top > data[i][j].top - offsetY && e.clientY - position.top < data[i][j].top + CELL_SIZE - offsetY) {
      								images[index].y = data[i][j].top;
      							}
      						}
      					}
      				}
      			}
      		});
      	}
  	}
});
  
  $("canvas").mouseup(function myUp(e) {
  	var position = $("canvas").position();
  	
  	for (var i = 0; i < ROWS; i++) {
  		for (var j = 0; j < COLS; j++) {
  			if (e.clientX - position.left > data[i][j].left - offsetX && e.clientX - position.left < data[i][j].left + CELL_SIZE - offsetX) {
  				
  				if (e.clientY - position.top > data[i][j].top - offsetY && e.clientY - position.top < data[i][j].top + CELL_SIZE - offsetY) {
  					data[i][j].value = images[index].id;
  				}
  			}
  		}
  	}
  	canvas.style.cursor = "default";
  	dragok = false;
  	$("canvas").mousemove = null;
  });
  
  $("canvas").mousemove(function(e) {
  	// position of mouse
  	var position = $('canvas').position();
  	
  	var x = e.clientX - position.left;
  	var y = e.clientY - position.top;
  	
  	if(x >= 700) {	// key left
  		if(offsetX < WIDTH - vWidth) {
  			offsetX += 5;
  		} else {
  			offsetX = WIDTH - vWidth;
  		}
  	} else if(x <= 100) { // key right
  		if(offsetX <= 0) {
  			offsetX = 0;
  		} else {
  			offsetX -= 5;
  		}
  	}
  });

  // save
  function Save() {
         // save to json file
         var enemies = [];
         var map = {
                 "level": LEVEL,
                 "enemies": enemies,
                 "data": ""
             }
         console.log(map);
  	var str = [];
  	for(var i = 0; i < ROWS; i++) {
  		for(var j = 0; j < COLS; j++) {
  		 
                 if(data[i][j].value == 12 || data[i][j].value == 13) {
                     var enemie = {
                         "col": i,
                         "row": j
                     }
                     enemies.push(enemie);
                     data[i][j].value = 0;
                 }
                 str.push(parseInt(data[i][j].value));
  		}
  	}
         map.enemies = enemies;
         map.data = str;
         
         // load json file
         $.getJSON('map_data.json', function(json) {
            // load successful
            // push new map
             json.maps.map.push(map);
             
             var mapStr = JSON.stringify(json);
             $.ajax({
                 url:"test-json.php",
                 data: "json=" + mapStr,
                 type: "POST",
                 success: function(p) {
                     alert("success");
                 }
             });
         });
         
  }  
</script>
